package com.java.process.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.model.process.ProcessTemplate;
import com.java.model.process.ProcessType;
import com.java.process.mapper.ProcessTemplateMapper;
import com.java.process.mapper.ProcessTypeMapper;
import com.java.process.service.ProcessService;
import com.java.process.service.ProcessTemplateService;
import com.java.process.service.ProcessTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ProcessTemplateServiceImpl extends ServiceImpl<ProcessTemplateMapper, ProcessTemplate> implements ProcessTemplateService {

    @Autowired
    private ProcessTemplateMapper processTemplateMapper;
    @Autowired
    private ProcessTypeMapper processTypeMapper;
    @Autowired
    private ProcessService processService;
    @Override
    public IPage<ProcessTemplate> selectPage(Page<ProcessTemplate> pageParam) {

        LambdaQueryWrapper<ProcessTemplate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(ProcessTemplate::getId);
        IPage<ProcessTemplate> page = processTemplateMapper.selectPage(pageParam,lambdaQueryWrapper);
        List<ProcessTemplate> pageRecords = page.getRecords();
        for(ProcessTemplate processTemplate:pageRecords){
            Long processTypeId = processTemplate.getProcessTypeId();
            ProcessType processType = processTypeMapper.selectById(processTypeId);
            if(processType==null){
                continue;
            }
            processTemplate.setProcessTypeName(processType.getName());
        }

        return page;
    }

    @Transactional
    @Override
    public void publish(Long id) {

        ProcessTemplate processTemplate = this.getById(id);
        processTemplate.setStatus(1);
        processTemplateMapper.updateById(processTemplate);

        //优先发布在线流程设计
        if(!StringUtils.isEmpty(processTemplate.getProcessDefinitionPath())) {
            processService.deployByZip(processTemplate.getProcessDefinitionPath());
        }
    }
}
